import { Empty, Spin } from 'antd';
import dynamic from 'next/dynamic';
import React, { useMemo } from 'react';
import { useSelector } from 'react-redux';
import {
  useSelectedDimensionsState,
  useSelectedSubFilterState,
  useSubFilterIsLoadingState,
} from '../components/subFilter/SubFilter';
import { ChartType, ComposedChartType, onCardClick } from '../libs/chartCommon';
import { refineFilterCondition } from '../libs/filterCommon';
import useCustomQuery from '../libs/hooks/useCustomQuery';
import useFilterMeta from '../libs/hooks/useFilterMeta';
import useSaLogging from '../libs/hooks/useSaLogging';
import { selectFilter } from '../libs/slices/filterSlice';

const ChartSelection = dynamic(() => import('../components/ChartSelection'));
const CardTemplate = dynamic(() => import('../components/templates/CardTemplate'));
const SubFilter = dynamic(() => import('../components/subFilter/SubFilter'));

export type DetailCardWrapperWithSubFilterProps = {
  title: string;
  chartType: ChartType;
  subFilterURI?: string;
  url: string;
  dimensions: string[];
  xlabel?: string;
  metrics: string[];
  subFilterData?: { name: string; type: string; value: string[] }[];
  dataLimit: number;
  yAxisPrefix?: string;
  composedChartMapping?: { [key: string]: ComposedChartType };
  showSubFilter: boolean;
  doTableSearch?: boolean;
};

function DetailCardWrapperWithSubFilter({
  title,
  chartType,
  subFilterURI,
  url,
  dimensions,
  xlabel,
  metrics,
  subFilterData,
  dataLimit,
  yAxisPrefix,
  composedChartMapping,
  showSubFilter,
  doTableSearch = true,
}: DetailCardWrapperWithSubFilterProps) {
  const selectedFilter = useSelector(selectFilter);
  const [selectedSubFilterState] = useSelectedSubFilterState();
  const [selectedDimensionState] = useSelectedDimensionsState();
  const [subFilterIsLoadingState] = useSubFilterIsLoadingState();
  const { saEvent } = useSaLogging();
  const { catalog } = useFilterMeta();

  const condition = useMemo(() => {
    return refineFilterCondition(selectedFilter, catalog);
  }, [selectedFilter]);

  const newCondition: any = useMemo(() => {
    return {
      conditions: {
        window: condition.conditions.window,
        ...selectedSubFilterState,
        productType: condition.conditions.productType,
        ...(!('location' in selectedSubFilterState) && {
          location: condition.conditions.location,
        }),
      },
    };
  }, [condition, selectedSubFilterState]);

  const newDimensions = useMemo(() => {
    return { dimensions: [...Object.values(selectedDimensionState), ...dimensions] };
  }, [dimensions, selectedDimensionState]);

  const dataFilter = useMemo(
    () => ({
      metrics,
      ...newCondition,
      ...newDimensions,
      dataLimit,
    }),
    [metrics, newCondition, newDimensions],
  );
  const { data, isLoading } = useCustomQuery({
    queryName: title,
    url,
    filter: dataFilter,
    enable: Object.values(selectedSubFilterState).length > 0,
  });
  const chartComponent = useMemo(() => {
    if (!isLoading && !data) return <Empty />;
    if (!isLoading && data) {
      return (
        <ChartSelection
          data={data}
          xlabel={xlabel}
          height="300px"
          chartType={chartType}
          metrics={metrics}
          stackedLabelPrefix={yAxisPrefix}
          composedChartMapping={composedChartMapping}
          doTableSearch={doTableSearch}
        />
      );
    }
    if (isLoading) return <Spin />;
    return <></>;
  }, [data, isLoading, chartType, subFilterIsLoadingState]);

  return (
    <CardTemplate
      isdashboard={false}
      title={title}
      content={chartComponent}
      onClick={event => onCardClick(event, data, saEvent, catalog)}
      showSubfilter={showSubFilter}
      subFilter={
        subFilterData && (
          <SubFilter
            title={title}
            subFilterURI={subFilterURI}
            subFilters={subFilterData}
            existAllOption={true}
          />
        )
      }
    />
  );
}

export default DetailCardWrapperWithSubFilter;
